import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
} from '@/api/user';
import { constantRoutes } from '@/router';
import { Getsingleperson } from '@/api/home/System settings/personal-information/index';
// import HOMEPAGE from '@/router/routes/client-modules/homepage';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import router from '@/router';
import { findIndex } from 'lodash';
import { UserState } from './types';
import useAppStore from '../app';
import useRouterStore from '../permission';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userId: undefined,
    name: undefined,
    mobile: undefined,
    positionId: undefined,
    positionName: undefined,
    code: '',
    masterUserStaffId: undefined,
    departmentId: undefined,
    roleId: undefined,
    roleName: '',
    menu: [],
    role: '',
    isSign: false,
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // // Get user's information
    // async info() {
    //   const res = await getUserInfo({ id: this.userId });
    //   this.setInfo(res);
    // },

    // Login
    async login(loginForm: any) {
      try {
        //
        // 请求登录接口
        const res = await userLogin({
          mobile: loginForm.username,
          password: loginForm.password,
        });
        if (res) this.isSign = true;
        setToken(res.access_token); // 储存token到localStorage
        this.userId = res.userId;
        // this.info();
        sessionStorage.setItem('userId', res.userId);
        // routerStore.generateRoutes();
        // sessionStorage.setItem('currMenus', JSON.stringify(HOMEPAGE)); // 每次登录将首页的路由菜单存放到
        const msg = await Getsingleperson({ id: res.userId });
        sessionStorage.setItem('loginInfo', JSON.stringify(msg)); // 登录后将登录人信息存储到localStorage
        sessionStorage.setItem('loginTime', new Date().toJSON());
      } catch (err) {
        clearToken();
        // throw err;
        return Promise.reject(err);
      }
    },
    logoutCallBack() {
      const routerStore = useRouterStore();
      this.$state = {
        userId: undefined,
        name: undefined,
        mobile: undefined,
        positionId: undefined,
        positionName: undefined,
        code: '',
        masterUserStaffId: undefined,
        departmentId: undefined,
        roleId: undefined,
        roleName: '',
        menu: [],
        role: '',
        isSign: false,
      };
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      sessionStorage.clear();
      localStorage.clear();
      routerStore.aRouterList = [];
      routerStore.isSignIn = false;
      // eslint-disable-next-line no-restricted-globals
      location.reload();
    },
    // Logout
    async logout() {
      // try {
      //   await userLogout();
      // } finally {
      this.logoutCallBack();
      // }
    },
  },
});

export default useUserStore;
